const log = require('../../util/log')
const config = require('../../util/config')
const logger = require('log4js').getLogger()

async function checkLoginTaobao(obj) {
    const {
        Network,
        Page,
        DOM,
        Runtime,
        Emulation
    } = this.client;
    obj = obj || {}
    obj.times = (obj.times || 0) + 1
    log('checking login taobao', obj)
    try {
        Page.navigate({
            url: 'https://pub.alimama.com/index.htm'
        })
        return step1.call(this, obj)
    } catch (err) {
        log(err)
    }
}

async function step1(obj) {
    const {
        Network,
        Page,
        DOM,
        Runtime,
        Emulation
    } = this.client;
    obj.times++
    if (obj.times > config.chromeMaxTimes) {
        return new Promise((resolve, reject) => {
            reject('超时')
        })
    }
    log('checking login taobao step 1', obj)
    try {
        var {result} = await Runtime.evaluate({expression: 'location.href'})
        if (result.value == 'https://pub.alimama.com/index.htm') {
            return step2.call(this, obj)
        }
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                step1.call(this, obj).then(result => {
                    resolve(result)
                }, result => {
                    reject(result)
                })
            }, 1000)
        })
    } catch (err) {
        log(err)
    }
}

async function step2(obj) {
    const {
        Network,
        Page,
        DOM,
        Runtime,
        Emulation
    } = this.client;
    obj.times++
    if (obj.times > config.chromeMaxTimes) {
        return new Promise((resolve, reject) => {
            reject('超时')
        })
    }
    log('checking login taobao step 2', obj)
    try {
        var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("span.logined-name")'})
        var cnt = result.description.substring(9, result.description.length - 1)
        if (cnt != 0) {
            return new Promise(resolve => {
                logger.debug('[' + __filename + ':' + __line + '] has login')
                this.qrcode = ''
                resolve(true)
            })
        }
        var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("iframe[name=taobaoLoginIfr]")'})
        var cnt = result.description.substring(9, result.description.length - 1)
        if (cnt != 0) {
            return new Promise(resolve => {
                logger.debug('[' + __filename + ':' + __line + '] has not login')
                resolve(false)
            })
        }
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                step2.call(this, obj).then(result => {
                    resolve(result)
                }, result => {
                    reject(result)
                })
            }, 1000)
        })
    } catch (err) {
        log(err)
    }
}

module.exports = checkLoginTaobao
